import {
  createError,
  defineEventHandler,
  getQuery,
  readBody,
  sendError,
} from 'h3';

// 初始补贴配置数据
const subsidyConfigs = [
  {
    id: 1,
    areaType: 'in',
    areaTypeText: '省内',
    amount: 0.8,
    effectiveDate: '2024-01-01',
    status: 'enable',
    statusText: '启用',
  },
  {
    id: 2,
    areaType: 'out',
    areaTypeText: '省外',
    amount: 1.2,
    effectiveDate: '2024-01-01',
    status: 'enable',
    statusText: '启用',
  },
];

export default defineEventHandler(async (event) => {
  const method = event.req.method;
  const url = event.req.url || '';
  const path = url.split('?')[0];
  const idMatch = path.match(/\/subsidy-config\/(\d+)$/);
  const statusMatch = path.match(/\/subsidy-config\/(\d+)\/status$/);

  try {
    switch (method) {
      case 'GET': {
        // 获取补贴配置列表
        if (path === '/subsidy-config') {
          const query = getQuery(event);
          const page = Number.parseInt(query.page as string) || 1;
          const pageSize = Number.parseInt(query.pageSize as string) || 20;

          // 分页处理
          const startIndex = (page - 1) * pageSize;
          const endIndex = startIndex + pageSize;
          const paginatedData = subsidyConfigs.slice(startIndex, endIndex);

          return {
            code: 0,
            data: {
              list: paginatedData,
              total: subsidyConfigs.length,
            },
          };
        }

        break;
      }
      case 'POST': {
        // 新增补贴配置
        if (path === '/subsidy-config') {
          const body = await readBody(event);

          // 生成新的ID
          const newId =
            Math.max(...subsidyConfigs.map((item: any) => item.id), 0) + 1;

          const newConfig = {
            id: newId,
            areaType: body.areaType,
            areaTypeText: body.areaType === 'in' ? '省内' : '省外',
            amount: Number.parseFloat(body.amount),
            effectiveDate: body.effectiveDate,
            status: 'enable',
            statusText: '启用',
          };

          subsidyConfigs.unshift(newConfig);

          return {
            code: 0,
            data: newConfig,
          };
        }

        break;
      }
      case 'PUT': {
        // 编辑补贴配置
        if (idMatch) {
          const id = Number.parseInt(idMatch[1]);
          const body = await readBody(event);

          const configIndex = subsidyConfigs.findIndex(
            (item: any) => item.id === id,
          );
          if (configIndex === -1) {
            return sendError(
              event,
              createError({ statusCode: 404, statusMessage: '补贴配置不存在' }),
            );
          }

          subsidyConfigs[configIndex] = {
            ...subsidyConfigs[configIndex],
            amount: Number.parseFloat(body.amount),
            effectiveDate: body.effectiveDate,
          };

          return {
            code: 0,
            success: true,
          };
        }

        // 切换补贴配置状态
        if (statusMatch) {
          const id = Number.parseInt(statusMatch[1]);
          const body = await readBody(event);

          const configIndex = subsidyConfigs.findIndex(
            (item: any) => item.id === id,
          );
          if (configIndex === -1) {
            return sendError(
              event,
              createError({ statusCode: 404, statusMessage: '补贴配置不存在' }),
            );
          }

          subsidyConfigs[configIndex].status = body.status;
          subsidyConfigs[configIndex].statusText =
            body.status === 'enable' ? '启用' : '停用';

          return {
            code: 0,
            success: true,
          };
        }

        break;
      }
      // No default
    }

    return sendError(
      event,
      createError({ statusCode: 404, statusMessage: 'API not found' }),
    );
  } catch (error) {
    console.error('Subsidy config API error:', error);
    return sendError(
      event,
      createError({ statusCode: 500, statusMessage: 'Internal Server Error' }),
    );
  }
});
